package com.xtx.controller.user;


import cn.dev33.satoken.stp.StpUtil;
import com.xtx.constant.JwtClaimsConstant;
import com.xtx.dto.UserLoginDto;
import com.xtx.entity.User;
import com.xtx.properties.JwtProperties;
import com.xtx.result.Result;
import com.xtx.service.UserService;
import com.xtx.utils.JwtUtil;
import com.xtx.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     * @param userLoginDto
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVo> userLogin(@RequestBody UserLoginDto userLoginDto){
        log.info("用户登录"+userLoginDto);
        User user = userService.userLogin(userLoginDto);
        Map<String , Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );
        StpUtil.login(user.getId());
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .id(user.getId())
                .name(user.getName())
                .userName(user.getUserName())
                .token(token)
                .build();
        return Result.success(userLoginVo);
    }
    @PutMapping("exit")
    public Result exitUser(Integer id){
        StpUtil.logout(id);
        return Result.success();
    }
}
